<template>
  <section class="todoapp">
    <TodoHeader @hadd="hadd"></TodoHeader>
    <TodoMain :list="showList" @hdel="hdel" @hchange='hchange' @changeall="changeall"></TodoMain>
    <TodoFooter :list='showList' @hclear = "hclear" @changetype="changetype"></TodoFooter>
  </section>
</template>

<script>
// 1.引入组件
import TodoHeader from "./components/TodoHeader.vue"
import TodoMain from "./components/TodoMain.vue"
import TodoFooter from "./components/TodoFooter.vue"
// 2.注册组件
// 3.使用组件
export default {
  components:{
    TodoHeader,
    TodoMain,
    TodoFooter
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('list')),
      type:'all'
    };
  },
  methods: {
    hdel(id) {
      const index = this.list.findIndex(item => item.id === id)
      this.list.splice(index,1)
    },
    hchange(id) {
      const obj = this.list.find(item => item.id === id)
      obj.isDone = !obj.isDone
    },
    hadd(msg) {
      this.list.push({
        name:msg,
        isDone:false,
        id:Date.now()
      })
    },
    hclear() {
      this.list = this.list.filter(item => !item.isDone)
    },
    changetype(type) {
      this.type = type
    },
    changeall(val) {
      this.list.forEach(item => item.isDone = val)
    }
  },
  computed: {
    showList() {
      if(this.type === 'all') {
        return this.list
      }else if(this.type === 'active') {
        return this.list.filter(item => !item.isDone)
      }else if(this.type === 'completed') {
        return this.list.filter(item => item.isDone)
      }
    }
  },
  watch: {
    list:{
      deep:true,
      handler() {
        localStorage.setItem('list',JSON.stringify(this.list))
      }
    }
  },
};
</script>

<style></style>
